package com.voicesys;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.voicesys.AutoAnswerIntentService.LocalBinder;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

public class ScreenButtonActivity extends Activity {

	private Intent service_intent;
	private static boolean service_running = false;
	private AutoAnswerIntentService autoAnswerIntentService;
	boolean mBound = false;
	boolean clickScreenButton = false;
	private Button screenButton;
	private Button turnSpeakerOffButton;
	private Button answerButton;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		raiseSound(getBaseContext());
		super.onCreate(savedInstanceState);

		service_intent = new Intent(this, AutoAnswerIntentService.class);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.on_call);
		// registerReceiver();

		screenButton = (Button) this.findViewById(R.id.screen);
		turnSpeakerOffButton = (Button) this.findViewById(R.id.turnOffSpeaker);
		answerButton = (Button) this.findViewById(R.id.answer);
		screenButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Thread thread = new Thread() {
					@Override
					public void run() {
						Looper.prepare();
						call();
					}
				};
				thread.start();

				// postScreenClickAction(screenButton, turnSpeakerOffButton,
				// answerButton);
				// autoAnswerIntentService.setFinished(false);
				// bindService(service_intent, mConnection, 0);
				// }
			}

		});

		turnSpeakerOffButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Thread thread = new Thread() {
					@Override
					public void run() {
						turnOffSpeakerHandling();
					}
				};
				thread.start();
				finish();
			}

			private void turnOffSpeakerHandling() {
				autoAnswerIntentService.stopRecording();
				try {
					autoAnswerIntentService.callReject();
				} catch (Exception e) {
					e.printStackTrace();
				}
				// AutoAnswerIntentService.endPhoneCall(getBaseContext());
				// endPhoneCall(getBaseContext());
				stopIntentService(service_intent);
			}
		});
		answerButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Thread thread = new Thread() {
					@Override
					public void run() {
						answerHandling();
					}
				};
				thread.start();

				finish();
			}

			private void answerHandling() {
				autoAnswerIntentService.stopRecording();
				AudioManager audioManager = (AudioManager) getApplicationContext()
						.getSystemService(Context.AUDIO_SERVICE);
				audioManager.setSpeakerphoneOn(false);
				audioManager.setMicrophoneMute(false);
				stopIntentService(service_intent);
			}
		});

	}

	private void call() {
		try {
			// add PhoneStateListener
			PhoneCallListener phoneListener = new PhoneCallListener();
			telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
			telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);

			Intent callIntent = new Intent(Intent.ACTION_CALL);
			callIntent.setData(Uri.parse(getString(R.string.autoDialer_number)));
			startActivity(callIntent);
		} catch (ActivityNotFoundException activityException) {
			activityException.printStackTrace();
		}
	}

	private void postScreenClickAction(final Button screenButton,
			final Button turnSpeakerOffButton, final Button answerButton) {
		screenButton.setVisibility(View.INVISIBLE);
		turnSpeakerOffButton.setVisibility(View.VISIBLE);
		answerButton.setVisibility(View.VISIBLE);
		// if
		// (!isServiceRunning("com.voicesys.AutoAnswerIntentService")) {
		startService(service_intent);
		bindService(service_intent, mConnection, Context.BIND_AUTO_CREATE);
	}

	private boolean isServiceRunning(String serviceClassName) {
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		List<RunningServiceInfo> runningServices = manager.getRunningServices(Integer.MAX_VALUE);
		for (RunningServiceInfo service : runningServices) {
			if (serviceClassName.equals(service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	@Override
	protected void onStart() {
		super.onStart();
		// Bind to LocalService

	}

	public AudioManager raiseSound(Context context) {
		AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		audioManager.setSpeakerphoneOn(true);
		audioManager.setMicrophoneMute(false);
		audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
				audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
				AudioManager.FLAG_PLAY_SOUND);
		return audioManager;
	}

	// @Override
	// protected void onResume() {
	// service_intent = new Intent(this, AutoAnswerIntentService.class);
	// // registerReceiver();
	//
	// super.onResume();
	// }

	// BroadcastReceiver receiver = new BroadcastReceiver() {
	//
	// @Override
	// public void onReceive(Context context, Intent intent) {
	// finish();
	//
	// }
	// };
	// @Override
	// protected void onStop() {
	// super.onStop();
	// stopService(new Intent(this, AutoAnswerIntentService.class));
	// }
	@Override
	protected void onStop() {
		super.onStop();
		// // Unbind from the service

	}

	private void stopIntentService(Intent intent) {
		if (mBound) {
			unbindService(mConnection);
			mBound = false;
		}
		// autoAnswerIntentService.setFinished(true);
		autoAnswerIntentService.stopService(service_intent);
	}

	// private void registerReceiver() {
	// IntentFilter filter = new IntentFilter();
	//
	// filter.addAction("com.finish.ACTIVITY");
	// registerReceiver(receiver, filter);
	// }
	/** Defines callbacks for service binding, passed to bindService() */
	private final ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			// We've bound to LocalService, cast the IBinder and get
			// LocalService instance
			LocalBinder binder = (LocalBinder) service;
			autoAnswerIntentService = binder.getService();
			mBound = true;
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			mBound = false;
		}
	};
	private TelephonyManager telephonyManager;

	// monitor phone call activities
	private class PhoneCallListener extends PhoneStateListener {

		private boolean isPhoneCalling = false;

		String LOG_TAG = "LOGGING 123";

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {

			if (TelephonyManager.CALL_STATE_RINGING == state) {
				// phone ringing
				System.out.println("PHONE RINGING....");
			}

			if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
				// active
				isPhoneCalling = true;
				System.out.println("PHONE ACTIVE ON CALL....");
				autoAnswerIntentService.answerPhoneCall();
			}

			if (TelephonyManager.CALL_STATE_IDLE == state) {
				System.out.println("PHONE CALL ENDED....");
				// run when class initial and phone call ended,
				// need detect flag from CALL_STATE_OFFHOOK
				if (isPhoneCalling) {
					// restart app
					Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(
							getBaseContext().getPackageName());
					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
					postScreenClickAction(screenButton, turnSpeakerOffButton, answerButton);
					isPhoneCalling = false;
					autoAnswerIntentService.startRecording(telephonyManager);
				}

			}
		}
	}

	public void postData(String url, String phoneNumber, String greetingFileName) {
		// Create a new HttpClient and Post Header
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);

		try {
			// Add your data
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("id", phoneNumber));
			nameValuePairs.add(new BasicNameValuePair("stringdata", greetingFileName));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			HttpResponse response = httpclient.execute(httppost);

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
	}

}